package com.tedu.mall.controller;

import com.tedu.mall.mapper.UserMapper;
import com.tedu.mall.pojo.User;
import com.tedu.mall.pojo.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    //从spring ioc容器取接口的代理对象
    @Autowired
    UserMapper userMapper;
    //登录
    @RequestMapping("/user/login")
    @CrossOrigin
    public User login(User user){
        //where username= and password
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=
                userExample.or();
        criteria.andUsernameEqualTo(user.getUsername());
        criteria.andPasswordEqualTo
                (user.getPassword());
        List<User> list=userMapper
                .selectByExample(userExample);
        //判断集合
        if (list !=null && list.size()>=1){
            //返回集合中用户信息
            User dbUser=list.get(0);
            //设置密码为null
            dbUser.setPassword("");
            return  dbUser;
        }
        //登录失败应该返回状态码
        return null;//报500

    }
    //注册
    @RequestMapping("/user/register")
    @CrossOrigin//允许别的网站用js访问我
    public String register(User user)
    {
        //查询数据库，判断用户是否存在
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.or();
        criteria.andUsernameEqualTo
                (user.getUsername());
        List<User> list=userMapper
                .selectByExample(userExample);
        if (list!=null && list.size()==0){
            //用户名不存在，可以注册
            int count=userMapper.insert(user);
            if (count>=1){
                return "注册成功";
            }else {
                return "注册失败";
            }
        }else {
            return "用户名已经存在";
        }

    }
    @RequestMapping("/test")
    public List<User> test(){
        return  userMapper.
                selectByExample(null);
    }
}
